package com.hinner.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hinner.common.Result;
import com.hinner.entity.R;
import com.hinner.entity.SysMenu;
import com.hinner.entity.SysRole;
import com.hinner.entity.SysUser;
import com.hinner.service.SysMenuService;
import com.hinner.service.SysRoleService;
import com.hinner.service.SysUserService;
import com.hinner.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 1.测试登录的接口：会给前端返回一个token
     * @return
     */
    @CrossOrigin
    @GetMapping("/user/login")
    public Result testLogin() {
        String token = JwtUtils.genJwtToken("习近平");
        return Result.success(token);
    }

    /**
     * 2.测试获取用户列表的接口：需要token验证，否则看不到返回信息
     * @param token
     * @return
     */
    @GetMapping("/user/sysList")
//    @PreAuthorize("hasRole('ROLE_admin1')") 判断角色：提前判断，必须有和这个角色才放行
//    @PreAuthorize("hasAuthority('system:role:delete1')")  // 判断权限
    public Result userList(@RequestHeader(required = false) String token) {
        if(StrUtil.isNotBlank(token)){
            List<SysUser> list = sysUserService.list();
            return Result.success(list);
        }else {
            return Result.error("请先登录");
        }

    }

    @GetMapping("/hello")
    public Result hello(){
        System.out.println("hello");
        return Result.success("hello");
    }

    @GetMapping("/name")
    public Result name(@RequestParam String username){
        String token = JwtUtils.genJwtToken(username);

        /*
            返回菜单树
            1. 根据用户名拿到用户信息
            2. 从而得到角色信息，菜单信息

         */
        SysUser currentUser = sysUserService.getUserByUserName(username);
        // 不需要对用户进行判空，因为在登录的时候已经判断过了，如果为空，就会抛出异常（走LoginFailureHandler）

        // 拿到角色关联的菜单信息
        Set<SysMenu> set = new HashSet<>();
        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id = " + currentUser.getId()));
        if (CollectionUtil.isNotEmpty(roleList)){
            for (SysRole role : roleList) {
                List<SysMenu> menuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "select menu_id from sys_role_menu where role_id = " + role.getId()));
                // 去重
                if (CollectionUtil.isNotEmpty(menuList)){
                    set.addAll(menuList);
                }
            }
        }
        List<SysMenu> list = new ArrayList<>(set);
        list.sort(Comparator.comparingInt(SysMenu::getOrderNum));

        // 构建菜单树
        List<SysMenu> menuList  = sysMenuService.buildMenuTree(list);
        System.out.println(menuList);


        // 多返回点内容
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("currentUser",currentUser);
        resultMap.put("menuList",menuList);
        return Result.success(resultMap);
    }
}
